/***************************************************************************/
var MAP = {};
/********************************手机App处理开始****************************/
/***************************************************************************/
//===============
var app = {
	// Application Constructor
	initialize: function() {
		document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
	},
	// deviceready Event Handler
	//
	// Bind any cordova events here. Common events are:
	// 'pause', 'resume', etc.
	onDeviceReady: function() {

		//页面加载时调用

		//填充localStorage到界面控件
		$('.username').val(localStorage.username);
		$('.userpassword').val(localStorage.userpassword);
	},
};

//本机指纹是否可用正确回调
function isAvailableSuccess(result) {
	//调取指纹验证界面
	//Android
	//Fingerprint.show({clientId: "Fingerprint-Demo",clientSecret: "password" }, fpsuccessCallback, fperrorCallback);
	//iOS
	touchid.authenticate(fpsuccessCallback, fperrorCallback, "请验证指纹");
}

//本机指纹是否可用错误回调
function isAvailableError(message) {
	layer.open({
		content: '该设备不支持指纹验证',
		skin: 'msg',
		time: 2 //2秒后自动关闭
	});
}

//指纹验证通过
function fpsuccessCallback() {

	//登录成功，界面改变登录状态；
	MAP.loginPanel.login($.trim(username), $.trim(userpassword));
}

//指纹验证不通过
function fperrorCallback(err) {
	layer.open({
		content: '指纹验失败',
		skin: 'msg',
		time: 2 //2秒后自动关闭
	});
}

/**********
登录流程处理
当点击登录时：
****/
function loginFunValid() {

	var username = $('.username').val(),
		userpassword = $('.userpassword').val();

	if($.trim(userpassword) == "" || $.trim(username) == "") {

		//为空，则退出判断，提示填写
		if($.trim($('.username').val()) == "" || $.trim($('.userpassword').val()) == "") {
			layer.open({
				content: '请填写用户名和密码',
				skin: 'msg',
				time: 2 //2秒后自动关闭
			});
			return;

		}
	}

	//开始登录
	MAP.loginPanel.login($.trim(username), $.trim(userpassword));
}

//检查已登录指纹状态
function checkFingerLogined() {
	//console.log("check logined.");
	//没有选择过，或者选择为false时，不使用指纹登录，返回false
	if(!localStorage.userfinger || localStorage.userfinger === false) {
		return false;
	} else {
		//Android
		//Fingerprint.isAvailable(isAvailableSuccess, isAvailableError);
		//iOS
		touchid.checkSupport(isAvailableSuccess, isAvailableError);

		//返回值说明：true表示已使用指纹登录，不显示登录界面。false则表示未使用指纹登录，显示登录界面。
		return true;
	}
}
//嵌入手机时，这句代码需取消注释，由Android开发操作
//app.initialize();

/***************************************************************************/
/********************************手机App处理结束****************************/
/***************************************************************************/

require([
	"esri/map", "esri/dijit/BasemapLayer",
	"esri/tasks/query", "esri/tasks/QueryTask", "esri/graphic", "esri/layers/FeatureLayer",
	"esri/symbols/MarkerSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/CartographicLineSymbol","esri/symbols/SimpleMarkerSymbol",
	"esri/InfoTemplate", "esri/renderers/SimpleRenderer", "esri/Color",
	"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom-construct", "esri/graphicsUtils",
	"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/GraphicsLayer",
	"esri/tasks/GeometryService", "esri/toolbars/draw", "esri/geometry/Point", "esri/geometry/Polyline", "esri/geometry/Polygon", "esri/SpatialReference",
	"esri/tasks/AreasAndLengthsParameters", "esri/tasks/LengthsParameters", "esri/geometry/geometryEngine",
	"esri/geometry/Extent", "esri/tasks/IdentifyTask", "esri/tasks/IdentifyParameters", "esri/tasks/IdentifyResult",
	"http://apps.bdimg.com/libs/vue/1.0.14/vue.min.js", "http://static.trmap.cn/x2js/xml2json.min.js", "dojo/domReady!"
], function(
	Map, BasemapLayer,
	Query, QueryTask, Graphic, FeatureLayer,
	MarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, CartographicLineSymbol,SimpleMarkerSymbol,
	InfoTemplate, SimpleRenderer, Color,
	Popup, PopupTemplate, domConstruct, graphicsUtils,
	ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer, GraphicsLayer,
	GeometryService, Draw, Point, Polyline, Polygon, SpatialReference,
	AreasAndLengthsParameters, LengthsParameters, geometryEngine,
	Extent, IdentifyTask, IdentifyParameters, IdentifyResult,
	Vue, X2JS
) {
	//	esri.config.defaults.io.proxyUrl = "http://jger.daoapp.io/whgis/proxy.jsp?";
	esri.config.defaults.io.proxyUrl = "http://117.34.70.42:26060/proxy/proxy.jsp?";
	esri.config.defaults.io.alwaysUseProxy = false;

	//测试网址
	var MAP_INFO_CONFIG = esri.config.defaults.io.proxyUrl + "http://27.17.26.116:8890/mapInfoconfig_dxh_new.xml";
	//最新网址
//	var MAP_INFO_CONFIG = esri.config.defaults.io.proxyUrl + "http://27.17.26.116:8890/mapInfoconfig_new.xml";

	//用户登录地址
	var LOGIN_SERVICE = "http://27.17.26.116:8019/MobileServer.asmx/Login";

	// 最大查询级别
	var SEARCH_SCALE = 40000.0;
	// 默认系统图层透明度
	var DEFAULT_OPACITY = 1.0;

	// 默认样式
	var POLYGON_SYMBOL = new SimpleFillSymbol();
	var LINE_SYMBOL = new CartographicLineSymbol(
		CartographicLineSymbol.STYLE_SOLID, // 线样式
		Color.fromHex("#009688"), // 颜色
		4, // 线宽
		CartographicLineSymbol.CAP_ROUND, // 线头样式-圆
		CartographicLineSymbol.JOIN_ROUND, // 相交线接头样式-圆
		5); // 线相交误差值
	var DEFAULT_MARKER = new MarkerSymbol({
		"url": "img/pin.png",
		"height": 50,
		"width": 23,
		"yoffset": 11,
		"type": "esriPMS"
	});

	// 图层定义
	var dmlayer = new GraphicsLayer();
	var dllayer = new GraphicsLayer();

	// 属性别名对照表
	var fieldAliases = {
		"BZ": "备注",
		"DWMC": "建设单位",
		"FZSJ": "发证时间",
		"HFXH": "省核发登记号",
		"GHYDXZ_DL": "规划用地性质大类",
		"GHYDXZ_ZL": "规划用地性质中类",
		"INSTANCEID": "业务编号",
		"JSDZ": "建设地址",
		"JSGM": "建设规模",
		"JZGD": "建筑高度",
		"JZMD": "建筑密度",
		"JZMJ": "建筑面积",
		"LHL": "绿地率",
		"LRDW": "录入单位",
		"OBJECTID": "OBJECTID",
		"PROJECTCODE": "项目编号",
		"QM": "所属区",
		"RJL": "容积率",
		"SHAPE_Area": "SHAPE_Area",
		"SHAPE_Length": "SHAPE_Length",
		"SM": "说明",
		"STATUS": "STATUS",
		"XKZWH": "工程许可证文号",
		"XMMC": "项目名称",
		"YDMJ": "用地面积",
		"YQSJ": "延期时间及日期",
		"重要说明": "重要说明"
	}

	function getKeyFromAlias(value) {
		for(var i in fieldAliases) {
			if(fieldAliases[i] === value) {
				return i;
			}
		}
	}

	function getAliasFromKey(key) {
		return fieldAliases[key];
	}

	function getIds(name) {
		switch(name) {
			case "选址意见书":
				return 3;
			case "用地许可证":
				return 2;
			case "建筑工程许可证":
				return 1;
			case "新增建设用地报批":
				return 0;
			case "土地征收":
				return 0;
			case "土地供应":
				return 0;
			case "土地整治_项目立项":
				return 4;
			case "土地整治_规划设计":
				return 5;
			case "土地整治_变更设计":
				return 5;
			case "土地整治_验收设计":
				return 5;
			case "渍水路段2016年7月2日13时":
				return 3;
			case "渍水点2016年7月6日9时":
				return 0;
			case "渍水点2016年7月6日16时":
				return 0;
			default:
				return name;
		}
	}

	// 弹出框
	var popup = new Popup({
		titleInBody: false,
		markerSymbol : new SimpleMarkerSymbol({
			"outline" : null,
			"color": [255,255,255,0]
		}),
		fillSymbol: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
			null, new Color([7, 0, 254, 1])
		)
	}, domConstruct.create("div"));

	// 弹出框内容模板
	var template = new PopupTemplate({
		title: "{NAME}",
		description: "名称:{NAME}",
		fieldInfos: [{
			fieldName: "NAME",
			label: "名称"
		}]
	});

	// 绘制工具
	var drawTool;

	// 各视图
	var vm_measurelayer, vm_search, vm_titlelayer, vm_projectlayer, vm_findProject, vm_bookPanel, locationBtn, vm_toolbar, loginPanel, systembar;

	// 初始化地图
	var map = new Map("map", {
		logo: false,
		slider: false,
		autoResize: true,
		infoWindow: popup
	});

	var _coords = [];
	var _draw_geometry;
	map.on("load", function() {
		map.addLayers([dmlayer, dllayer]); // 增加矢量图层
		map.on("click", identifyClick);

	});

	// 查询方法
	function identifyClick(e) {
		console.log(map.getScale());
		if(map.getScale() > SEARCH_SCALE) {
			return;
		}

		// 需要查询的任务数量
		var _layers = [];
		_layers = _layers.concat(project_tree, titletree);
		console.log(_layers);
		var _length = _layers.length;
		if(_length === 0) {
			map.infoWindow.hide();
			return;
		}

		var searchLayer = layer.open({
			type: 2,
			shadeClose: false,
			content: "查询中...",
			//time: 15 //15秒后自动关闭
		});

		//组织查询参数
		var identifyParams = new IdentifyParameters();
		identifyParams.geometry = e.mapPoint;
		identifyParams.mapExtent = map.extent;
		identifyParams.tolerance = 3;
		identifyParams.returnGeometry = true;
		identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;

		var _mask = 0; // 标记查询任务完成情况。当与任务长度一致时结束查询状态，显示查询结果。

		var resultsList = [];
		for(var _i in _layers) {
			var _layer = map.getLayer(_layers[_i]);
			if(!_layer) {
				_mask++;
				continue;
			}
			var _url = _layer.url;
			var _task = new IdentifyTask(_url);
			_task.execute(identifyParams, function(results) {
				resultsList = resultsList.concat(results);
				_mask++;
			}, function(error) {
				console.log(error);
				_mask++;
			});
		}

		// 循环等待查询结果，等待执行间隔为500毫秒
		var _searching = window.setInterval(function() {
			// 等待查询结果返回完毕
			if(_mask == _length) {
				var fs = [];
				clearInterval(_searching); //任务执行完毕，取消循环查询
				console.log(resultsList);
				for(var i in resultsList) {
					var res = resultsList[i];
					res.feature.setInfoTemplate(autoFields(res.feature));
					fs.push(res.feature);
				}
				if(fs.length == 0) {
					layer.close(searchLayer);
					//提示
					layer.open({
						content: "查无结果",
						skin: "msg",
						time: 2 //2秒后自动关闭
					});
					map.infoWindow.hide();
				} else {
					layer.close(searchLayer);
					map.infoWindow.setFeatures(fs);
					map.infoWindow.show(e.mapPoint);
				}

			} else {
				console.log("查询中...");
			}
		}, 500);
	}

	$(document).ready(jQueryReady);

	// jquery
	function jQueryReady() {
		// 地图初始化入口
		var init = function() {
			// 判断登陆信息是否合法
			if(!window.localStorage.User) {
				// 如无用户信息则返回登陆界面
				window.location.href = "loginReg.html";
			}

			// 反序列化json字符串为对象
			var _user = JSON.parse(window.localStorage.User);

			// 请求图层配置信息
			$.ajax({
				type: "GET",
				url: esri.config.defaults.io.proxyUrl + _user.FileUrl,
				success: _mapAppInit
			});
		};

		//程序初始化方法
		var _mapAppInit = MAP.mapAppInit = function(result) {
			// 读取图层配置
			dojoConfig.appdata = new X2JS().xml2json(result.children[0]);
			console.log(dojoConfig.appdata);

			// 创建基础底图
			_createBaseMaps();
			// 图层
			_createTitleLayers();
			// 项目图层
			_createProjectTree();
			
			// 创建蒙版层
			var shadeLayer = new ArcGISTiledMapServiceLayer("http://27.17.26.115:8399/arcgis/rest/services/DXHMOBILE/DXHMB/MapServer")//new GraphicsLayer();
			// 加入图层
			map.addLayer(shadeLayer);
			
			// 搜索视图
			vm_search = new Vue({
				el: ".searchPanel",
				data: {
					state: "A", // 视图状态，A是地名，B是道路
					showSearch: false, // 搜索框打开
					open: false, // 搜索结果打开
					searchText: "", // 搜索文本
					searchCount: 0, //poi总数
					featureSet: [], //POI结果列表
					dl_searchCount: 0, //道路总数
					DLFeatures: [], //道路结果列表
					jobNotice: 0, // 任务完成提醒 当计数器为2时，关闭查询框
					isPlaceBasic: false,
					isRoadBasic: true,
					searchingLayer: null,
				},
				methods: {
					doSearch: function() {
						var that = this;
						that.jobNotice = 0; // 重置计数器
						if(!that.searchText) {
							//提示
							layer.open({
								content: "请输入搜索条件",
								skin: "msg",
								time: 2 //2秒后自动关闭
							});
							return;
						}
						that.searchingLayer = layer.open({
							type: 2,
							shadeClose: false,
							content: "查询中...",
							//time: 15 //15秒后自动关闭
						});
						that._DMSearch(this.searchText);
						that._DLSearch(this.searchText);
					},

					// 地名查询
					_DMSearch: function(searchText) {
						var that = this;
						var DMDZ_SERVICE = dojoConfig.appdata.dmdz_service.url;
						var dmTask = new QueryTask(DMDZ_SERVICE + "/0"); // 地名
						var dmq = new Query();
						dmq.where = "NAME like '%" + searchText + "%'";
						dmq.returnGeometry = true;
						dmq.outFields = ["*"];
						dmTask.executeForCount(dmq, function(count) {
							that.searchCount = count;
							if(count != 0) {
								//dmTask.executeForIds(dmq, function(ids) {
								//console.log(ids);
								dmTask.execute(dmq, function(results) {
									// 加入列表
									that.featureSet = results.features
										// 绘制到地图
									_drawGraphics(results.features, "dmlayer");
									if(that.jobNotice == 1) {
										that.open = true;
										layer.close(that.searchingLayer); //关闭信息框
									} else {
										that.jobNotice += 1;
									}
								});
								//});
							} else {
								if(vm_search.jobNotice == 1) {
									vm_search.open = true;
									layer.close(that.searchingLayer); //关闭信息框
								} else {
									vm_search.jobNotice += 1;
								}
							}
						}, function(err) {
							if(vm_search.jobNotice == 1) {
								vm_search.open = true;
								layer.close(that.searchingLayer); //关闭信息框
							} else {
								vm_search.jobNotice += 1;
							}
						});
					},

					// 道路查询
					_DLSearch: function(searchText) {
						var that = this;
						var DMDZ_SERVICE = dojoConfig.appdata.dmdz_service.url;
						var dlTask = new QueryTask(DMDZ_SERVICE + "/1"); // 道路
						var dlq = new Query();
						dlq.where = "NAME like '%" + searchText + "%'";
						dlq.returnGeometry = true;
						dlq.outFields = ["*"];
						dlTask.executeForCount(dlq, function(count) {
							vm_search.dl_searchCount = count;
							if(count != 0) {
								dlTask.execute(dlq, function(results) {
									// 加入列表
									vm_search.DLFeatures = results.features
										// 绘制到地图
									_drawGraphics(results.features, "dllayer");
									if(vm_search.jobNotice == 1) {
										vm_search.open = true;
										layer.close(that.searchingLayer); //关闭信息框
									} else {
										vm_search.jobNotice += 1;
									}
								});
							} else {
								if(vm_search.jobNotice == 1) {
									vm_search.open = true;
									layer.close(that.searchingLayer); //关闭信息框
								} else {
									vm_search.jobNotice += 1;
								}
							}
						}, function(err) {
							console.log(err);
							if(vm_search.jobNotice == 1) {
								vm_search.open = true;
								layer.closeAll(); //关闭信息框
							} else {
								vm_search.jobNotice += 1;
							}
						});
					},

					closeSearch: function() {
						vm_toolbar._searchDestroy();
						this.close();
					},
					//关闭清空
					close: function() {
						this.showSearch = false;
						this.open = false;
						this.searchText = "";
						this.searchCount = 0;
						this.featureSet = []; //结果列表
						map.infoWindow.hide();
						dllayer.clear();
						dmlayer.clear();
					},

					//定位显示
					location: function(event) {
						//============================================
						// 项目选中后续逻辑
						var _contents = $('.searchResult .item');
						_contents.css('background-color', '');
						var _target = $(event.target).hasClass("item") ? $(event.target) : $(event.target).parent();
						_target.css('background-color', '#5FB878');
						//============================================

						console.log(event.currentTarget)
						var _gid = parseInt($(event.currentTarget).attr("gid")); //获取OBJID 并转为数字型
						console.log(_gid);
						if(this.state === "A") {
							// 定位显示地名
							$(dmlayer.graphics).each(function(_, g) {
								var _id = g.attributes.OBJECTID
								if(_id === _gid) {
									map.infoWindow.setFeatures([g]);
									map.infoWindow.show(g.geometry);
									map.centerAndZoom(g.geometry, 12);
									return;
								}
							});
						} else {
							// 道路定位弹出
							$(dllayer.graphics).each(function(_, g) {
								var _id = g.attributes.OBJECTID
								if(_id === _gid) {
									map.infoWindow.setFeatures([g]);
									var index = Math.round(g.geometry.paths[0].length / 2);
									var center = g.geometry.getPoint(0, index);
									map.infoWindow.show(center);
									map.centerAndZoom(center, 12);
									return;
								}
							});
						}
					}
				},
				watch: {
					"state": function(val, old) {
						if(val === "A") {
							this.isPlaceBasic = !this.isPlaceBasic;
							this.isRoadBasic = true;
							map.infoWindow.hide();
							dmlayer.show();
							dllayer.hide();
						} else {
							this.isRoadBasic = !this.isRoadBasic;
							this.isPlaceBasic = true;
							map.infoWindow.hide();
							dmlayer.hide();
							dllayer.show();
						}
					}
				}
			});
			vm_search.$watch("searchText", function() {
				vm_search.open = false;
				vm_search.searchCount = 0;
				vm_search.featureSet = [] //结果列表
				map.infoWindow.hide();
				dllayer.clear();
				dmlayer.clear();
			});

			// 图层视图
			vm_titlelayer = new Vue({
				el: ".layerPanel",
				data: {
					showLayer: false,
					_MAPEVENT: null
				}
			});

			// 项目图层视图
			vm_measurelayer = new Vue({
				el: ".measurePanel",
				data: {
					drawing: false, // 是否正在绘制
					showResult: false,
					showMeasure: false, // 测量面板显示控制参数
					measureIndex: 0, // 默认当前显示的数组索引,新增后自动增长，上一页下一页控制参数
					graphicCount: 0, // 记录总数,用于判断向前后的可用性
					measureGraphics: [], // 保存测量对象的数组 ， 对象结构 Graphic
					target: null, // 选中的目标模型
					isPointActive: false,
					isLineActive: false,
					isPolygonActive: false
				},
				methods: {
					// 画点
					drawPoint: function() {
						this.target = null;
						map.graphics.clear();
						_coords = [];
						//drawTool.activate(Draw.POINT)
						this.drawing = true;
						this.showResult = false;
						this.isPointActive = true;
						this.isLineActive = false;
						this.isPolygonActive = false;
					},
					drawLine: function() {
						this.target = null;
						map.graphics.clear();
						_coords = [];
						//drawTool.activate(Draw.POLYLINE)
						this.drawing = true;
						this.showResult = false;
						this.isActive = !this.isActive;
						this.isLineActive = true;
						this.isPointActive = false;
						this.isPolygonActive = false;
					},
					drawPolygon: function() {
						this.target = null;
						map.graphics.clear();
						_coords = [];
						//drawTool.activate(Draw.POLYGON)
						this.drawing = true;
						this.showResult = false;
						this.isPolygonActive = true;
						this.isLineActive = false;
						this.isPointActive = false;
					},
					showInfo: function() {
						// 显示绘制结果信息
						this.showResult = true;
						var _mg = vm_measurelayer.measureGraphics[this.measureIndex]; // 获取最新要素
						map.graphics.clear(); // 清空现有绘制数据
						map.graphics.add(_mg.graphic); // 添加新的要素
						this.target = _mg;

					},
					prepage: function() {
						this.measureIndex -= 1;
						this.showInfo();
					},
					nextpage: function() {
						this.measureIndex += 1;
						this.showInfo();
					},
					clean: function() {
						//drawTool.deactivate();
						this.drawing = false;
						map.graphics.clear();
						this.measureGraphics = [];
						this.isPointActive = false;
						this.isLineActive = false;
						this.isPolygonActive = false;
					},
					drop: function() {
						//drawTool.deactivate();
						this.drawing = false;
						this.isPointActive = false;
						this.isLineActive = false;
						this.isPolygonActive = false;

						if(this.target) {
							this.measureGraphics.pop();
						}

						this.target = null;
						this.showInfo();
					},
					close: function() {
						//drawTool.deactivate();
						this.drawing = false;
						dmlayer.clear();
						dllayer.clear();
						this.isPointActive = false;
						this.isLineActive = false;
						this.isPolygonActive = false;
					}
				},
				events: {
					MEASURE_EVENT: null // 量算时间
				},
				watch: {
					"showMeasure": function(n, o) {
						var that = this;
						if(o) {
							that.$options.events.MEASURE_EVENT.remove();
							return;
						}
						that.$options.events.MEASURE_EVENT = map.on('click', function(e) {

							var _drawing = that.drawing;

							// 判断当前是否为绘制状态
							if(_drawing === false) {
								return;
							}

							// 开始绘制显示结果面板，用于动态显示测量结果
							vm_measurelayer.showResult = true;

							// 判断绘制类型
							var _drawType = that.isPointActive ? "point" : (that.isLineActive ? "line" : "polygon");

							// 画点
							if(_drawType === "point") {
								// 可以明确绘制的开始和终止
								drawingMeasure(e.mapPoint);
							} else {
								// 获取点击的坐标位置，提供绘制
								var _coord = [e.mapPoint.x, e.mapPoint.y];
								// 绘制线和面，没有明确的终止
								if(_drawType === "line") {
									// 将坐标点推送到点坐标列表里
									_coords.push(_coord);
									if(_coords.length === 1) { // 等于2的时候显示一条辅助线
										var _g = new Graphic(e.mapPoint, DEFAULT_MARKER);
										map.graphics.add(_g);
									}
									// 大于两点开始构线
									if(_coords.length >= 2) {
										_draw_geometry = new Polyline(_coords);
										_draw_geometry.setSpatialReference(map.spatialReference); //设置空间索引
										drawingMeasure(_draw_geometry); // 绘制
									}
								} else if(_drawType === "polygon") {
									_coords.reverse();
									_coords.push(_coord);
									_coords.reverse();
									if(_coords.length === 1) { // 等于2的时候显示一条辅助线
										var _g = new Graphic(e.mapPoint, DEFAULT_MARKER);
										map.graphics.add(_g);
									}
									if(_coords.length === 2) { // 等于2的时候显示一条辅助线
										map.graphics.clear();
										var line = new Polyline(_coords);
										var _g = new Graphic(line, LINE_SYMBOL);
										map.graphics.add(_g);
									}
									if(_coords.length >= 3) {
										map.graphics.clear();
										_draw_geometry = new Polygon(_coords);
										_draw_geometry.setSpatialReference(map.spatialReference);
										drawingMeasure(_draw_geometry);
									}
								}
							}
						});
					}
				}
			});
			vm_measurelayer.$watch("measureGraphics", function() {
				var length = vm_measurelayer.measureGraphics.length; // 获取长度
				if(length === 0) {
					vm_measurelayer.measureIndex = 0;
					vm_measurelayer.graphicCount = length;
					this.target = null;
					return;
				}
				vm_measurelayer.showResult = true;
				vm_measurelayer.graphicCount = length;
				var _mg = vm_measurelayer.measureGraphics[length - 1]; // 获取最新要素
				map.graphics.clear(); // 清空现有绘制数据
				map.graphics.add(_mg.graphic); // 添加新的要素
				vm_measurelayer.measureIndex = length - 1;
				this.target = _mg;
				vm_measurelayer.showInfo();
			});

			// 项目图层视图
			vm_projectlayer = new Vue({
				el: ".projectPanel",
				data: {
					showProject: false,
				}
			});

			//项目查询视图
			vm_findProject = new Vue({
				el: ".findPanel",
				created: function() {
					this.projects = generateProjectSelection();
					$("#projects").dropdown({
						allowReselection: true,
						onChange: function(e) {
							// 刷新子属性
							vm_findProject.flushFields(e);
						}
					});

					$("#fields").dropdown({
						allowReselection: true,
						onChange: function(e) {
							vm_findProject.field = e
						}
					});
				},
				data: {
					showFind: false,
					showResult: false,
					projects: [],
					fields: [],
					project: {},
					field: "",
					findText: "",
					results: [], // 查询的结果
					_layer: null
				},
				methods: {
					find: function() {
						// 项目数据查询
						var currProject = this.project;
						this._createFeatureLayer(currProject);
						var _queryTask = new QueryTask(currProject.url + "/" + currProject.layerids);
						var _query = new Query();
						_query.where = this.field + " like " + "'%" + this.findText + "%'";
						_query.returnGeometry = true;
						_query.outFields = ["*"];
						_queryTask.execute(_query, function(result) {
							vm_findProject.showResult = true;
							vm_findProject.results = result.features;
						});
					},
					clean: function() {
						map.removeLayer(this._layer);
						this.showResult = false;
						this.results = [];
						this.findText = "";
						map.infoWindow.hide();
					},
					location: function(e) {

						//============================================
						// 项目选中后续逻辑
						var _contents = $('.findResult .item');
						_contents.css('background-color', '');
						var _target = $(event.target).hasClass("item") ? $(event.target) : $(event.target).parent();
						_target.css('background-color', '#5FB878');
						//============================================

						var _gid = parseInt($(event.currentTarget).attr("gid")); //获取OBJID 并转为数字型
						var query = new Query();
						query.where = "OBJECTID = " + _gid;
						query.outFields = ["*"];
						query.returnGeometry = true;
						this._layer.selectFeatures(query, FeatureLayer.MODE_SELECTION, function(result) {
							var feature = result[0];
							feature.setInfoTemplate(vm_findProject._autoFields(feature))
							var extent = graphicsUtils.graphicsExtent(result);
							map.infoWindow.setFeatures(result);
							map.infoWindow.show(extent.getCenter());
							map.setExtent(extent);
							map.centerAt(extent.getCenter());
						});

					},
					_createFeatureLayer: function(project) {
						if(this._layer) {
							map.removeLayer(this._layer);
							map.infoWindow.hide();
							this._layer = null;
						}
						this._layer = new FeatureLayer(project.url + "/" + project.layerids, {
							infoTemplate: this._autotemplate(project.outfileds),
							outFields: ["*"]
						});
						this._layer.setDefinitionExpression(this.field + " like " + "'%" + this.findText + "%'");
						map.addLayer(this._layer);
					},
					_autotemplate: function(fields) {
						var _fields = fields.split(",");
						var _fieldInfos = [];
						for(var f in _fields) {
							if(!getKeyFromAlias(_fields[f]))
								continue;
							_fieldInfos.push({
								fieldName: getKeyFromAlias(_fields[f]),
								visible: true,
								label: _fields[f]
							});
						}
						return new PopupTemplate({
							fieldInfos: _fieldInfos
						});
					},
					_autoFields: function(feature) {
						var attr = feature.attributes;
						var _fieldInfos = [];
						for(var a in attr) {
							if(a === "OBJECTID" || a === "Shape" || a === "Shape_Length" || a === "Shape_Area" ||
								a === "SHAPE_Length" || a === "SHAPE_Area") {
								continue;
							}
							if(!attr[a] || attr[a] === "Null") {
								continue;
							}
							_fieldInfos.push({
								fieldName: a,
								visible: true,
								label: getAliasFromKey(a)
							});
						}
						return new PopupTemplate({
							fieldInfos: _fieldInfos
						});
					},
					flushFields: function(e) {
						vm_findProject.fields = [];
						$("#fields").dropdown('restore defaults')
						$(this.projects).each(function(k, v) {
							if(e === v.text) {
								vm_findProject.project = v;
								$(v.outfileds.split(",")).each(function(i, n) {
									vm_findProject.fields.push({
										"text": n,
										"value": getKeyFromAlias(n)
									})
								})
							}
						});
					}
				}
			});

			vm_bookPanel = new Vue({
				el: ".bookPanel",
				created: function() {
					for(var key in localStorage) {
						var _kp = key.split("_");
						if(_kp[0] !== "bookmark") {
							continue;
						}
						var _ext = localStorage.getItem(key);

						var _eo = JSON.parse(_ext);

						this.bookArray.push({
							"bookName": _kp[1],
							"extent": _eo
						});
					}
				},
				data: {
					showBook: false,
					bookName: "",
					bookArray: []
				},
				methods: {
					addBookMark: function() {
						var _extentString = JSON.stringify({
							"xmin": map.extent.xmin,
							"xmax": map.extent.xmax,
							"ymin": map.extent.ymin,
							"ymax": map.extent.ymax
						});

						var _key = "bookmark_" + this.bookName;

						localStorage.setItem(_key, _extentString);

						var _eo = JSON.parse(_extentString);

						this.bookArray.push({
							"bookName": this.bookName,
							"extent": _eo
						})
					},
					setExtent: function(_eo) {
						console.log(_eo);

						var extent = new Extent({
							"xmin": _eo.xmin,
							"xmax": _eo.xmax,
							"ymin": _eo.ymin,
							"ymax": _eo.ymax,
							"spatialReference": map.spatialReference
						});

						map.setExtent(extent, true);
					},
					delete: function(index, key) {
						var _key = "bookmark_" + key;
						localStorage.removeItem(_key);
						this.bookArray.splice(index, 1);
					}
				}
			});
			
			// 定位矢量层
			var locationLayer;
			locationBtn = new Vue({
				el: '.positionMapIon',
				created: function() {
					if(navigator.geolocation) {
						//navigator.geolocation.getCurrentPosition(function(position) {
						//WGS2BJ54(position.coords)
						//});
						locationLayer = new GraphicsLayer();
						map.addLayer(locationLayer);
						this.getPosition();
					} else {
						layer.open({
							content: "浏览器不支持定位",
							skin: "msg",
							time: 2 //2秒后自动关闭
						});
					}
				},
				methods: {
					getPosition: function() {
						var LOCATION_PIN = new MarkerSymbol({
							"url": "img/location.png",
							"height": 18,
							"width": 18,
							"yoffset": 8,
							"type": "esriPMS"
						});
						navigator.geolocation.getCurrentPosition(function(position) {
							console.log(position);
							var coords = position.coords;
							var BJ54 = WGS2BJ54(position.coords, function(x, y) {
								console.log(x, y);
								var position = new Point(x, y, map.spatialReference);
								var _g = new Graphic(position, LOCATION_PIN);
								locationLayer.add(_g);
								map.centerAt(position);
							});
						}, function(error) {
							var msg;
							switch(error.code) {
								case error.PERMISSION_DENIED:
									msg = "用户拒绝对获取地理位置的请求。"
									break;
								case error.POSITION_UNAVAILABLE:
									msg = "位置信息是不可用的。"
									break;
								case error.TIMEOUT:
									msg = "请求用户地理位置超时。"
									break;
								case error.UNKNOWN_ERROR:
									msg = "未知错误。"
									break;
							}
							layer.open({
								content: msg,
								skin: "msg",
								time: 2 //2秒后自动关闭
							});
						});
					},
					
					// 隐藏显示图层
					toggleShow:function(){
						if(locationLayer.visible) {
							locationLayer.hide();
						} else {
							locationLayer.show();
						}
					}
				}
			});

			function generateProjectSelection() {
				var dynamic_map = dojoConfig.appdata.dynamic_map.node;
				var _treedata = [];
				$(dynamic_map).each(function(k, v) {
					if(v._nodeType == "Group") {
						_generateChildren(v, _treedata);
					} else {
						var _layerids = v.layerids;
						if(!_layerids) {
							_layerids = getIds(v.name)
						}
						var layer = {
							"icon": "esri-icon-feature-layer",
							"text": v.name,
							"url": v.url,
							"type": v.LayerType,
							"nodeType": v.nodeType,
							"outfileds": v.outfields,
							"layerids": _layerids
						};
						layer.icon = "esri-icon-layers";
						_treedata.push(layer);
					}
				});
				return _treedata;
			}

			function _generateChildren(_v, _list) {
				if(_v._nodeType == "Group") {
					$(_v.node).each(function(i, n) {
						_generateChildren(n, _list);
					});
				} else {
					var layer = {
						"icon": "esri-icon-feature-layer",
						"text": _v.name,
						"url": _v.url,
						"type": _v.LayerType,
						"nodeType": _v._nodeType,
						"outfileds": _v.outfields,
						"layerids": _v.layerids
					};
					layer.icon = "esri-icon-layers";
					_list.push(layer);
				}
			}

			// 基础图层控制
			vm_toolbar = new Vue({
				el: ".toolbar",
				data: {
					// 搜索样式切换
					searchClass: {
						unselect: true,
						selected: false
					},
					layerClass: {
						unselect: true,
						selected: false
					},
					measureClass: {
						unselect: true,
						selected: false
					},
					projectClass: {
						unselect: true,
						selected: false
					},
					findClass: {
						unselect: true,
						selected: false
					},
					bookClass: {
						unselect: true,
						selected: false
					}
				},
				methods: {
					//==========search dmdz===============
					search: function() {
						if(this.searchClass.selected) {
							vm_search.doSearch();
						} else {
							vm_search.showSearch = true;
							this._searchInit();
						}
					},
					_searchInit: function() {
						// 搜索初始化
						this._layerDestroy();
						this._projectDestroy();
						this._measureDestroy();
						this._findDestroy();
						this._bookDestroy();
						this.searchClass.unselect = false;
						this.searchClass.selected = true;
					},
					_searchDestroy: function() {
						this.searchClass.unselect = true;
						this.searchClass.selected = false;
					},
					//==========title layer===============
					layer: function() {
						if(!vm_titlelayer.showLayer)
							this._layerInit();
						else
							this._layerDestroy();
					},
					_layerInit: function() {
						vm_search.closeSearch();
						this._projectDestroy();
						this._measureDestroy();
						this._findDestroy();
						this._bookDestroy();
						this.layerClass.unselect = false;
						this.layerClass.selected = true;
						vm_titlelayer.showLayer = true;
					},
					_layerDestroy: function() {
						this.layerClass.unselect = true;
						this.layerClass.selected = false;
						vm_titlelayer.showLayer = false;
					},
					//==========measure===============
					measure: function() {
						// 激活量算绘制状态
						if(!vm_measurelayer.showMeasure)
							this._measureInit();
						else
							this._measureDestroy();
					},
					_measureInit: function() {
						// 启动量算面板
						vm_search.closeSearch();
						this._layerDestroy();
						this._projectDestroy();
						this._findDestroy();
						this._bookDestroy();
						this.measureClass.unselect = false;
						this.measureClass.selected = true;
						vm_measurelayer.showMeasure = true;
					},
					_measureDestroy: function() {
						vm_measurelayer.clean();
						// 关闭量算面板
						this.measureClass.unselect = true;
						this.measureClass.selected = false;
						vm_measurelayer.showMeasure = false;
						vm_measurelayer.close();
					},
					//==========project layer===============
					project: function() {
						if(!vm_projectlayer.showProject)
							this._projectInit();
						else
							this._projectDestroy();
					},
					_projectInit: function() {
						vm_search.closeSearch();
						this._layerDestroy();
						this._measureDestroy();
						this._findDestroy();
						this._bookDestroy();
						this.projectClass.unselect = false;
						this.projectClass.selected = true;
						vm_projectlayer.showProject = true;
					},
					_projectDestroy: function() {
							this.projectClass.unselect = true;
							this.projectClass.selected = false;
							vm_projectlayer.showProject = false;
						}
						//==========find project==============
						,
					find: function() {
						if(!vm_findProject.showFind)
							this._findInit();
						else
							this._findDestroy();
					},
					_findInit: function() {
						vm_search.closeSearch();
						this._layerDestroy();
						this._measureDestroy();
						this._projectDestroy();
						this._bookDestroy();
						this.findClass.unselect = false;
						this.findClass.selected = true;
						vm_findProject.showFind = true;
					},
					_findDestroy: function() {
						this.findClass.unselect = true;
						this.findClass.selected = false;
						vm_findProject.showFind = false;
					},
					//=============书签管理=============
					book: function() {
						if(!vm_bookPanel.showBook)
							this._bookInit();
						else
							this._bookDestroy();
					},
					_bookInit: function() {
						vm_search.closeSearch();
						this._layerDestroy();
						this._measureDestroy();
						this._projectDestroy();
						this._findDestroy();
						this.bookClass.unselect = false;
						this.bookClass.selected = true;
						vm_bookPanel.showBook = true;
					},
					_bookDestroy: function() {
						this.bookClass.unselect = true;
						this.bookClass.selected = false;
						vm_bookPanel.showBook = false;
					},
					position: function() {
						locationBtn.getPosition();
						locationBtn.getPosition();
					}
				}

			});

			// 系统功能菜单
			systembar = new Vue({
				el: ".systembar",
				methods: {
					show: function() {
						loginPanel.showLogin = !loginPanel.showLogin;
					},
					help: function() {
						/*
						 //window.location.href = "help.html";
						 var pageii = layer.open({
						 type: 1,
						 content: "<button onclick='layer.closeAll()'>关闭</button><embed src='http://27.17.26.116:8890/files/%E6%8C%87%E6%A0%87%E4%BD%93%E7%B3%BB.pdf' style='position: absolute;height: 100%;width: 100%;margin: 0;padding: 0;overflow: hidden;'></embed>",
						 anim: 'up',
						 style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
						 });*/
						window.open("http://27.17.26.116:8890/files/%E6%8C%87%E6%A0%87%E4%BD%93%E7%B3%BB.pdf");
					}
				}
			});

			// 登录组件绑定到全局变量
			MAP.loginPanel = loginPanel = new Vue({
				el: ".loginPanel",
				data: {
					showLogin: false,
					state: "LOGINED", //LOGIN
					//name: device.uuid,
					User: null
				},
				methods: {
					// 用户登录
					login: function(username, password) {
						$.post(esri.config.defaults.io.proxyUrl + LOGIN_SERVICE, {
							"name": username,
							"password": password,
							//iOS
							"devInfo": device.uuid
								//Android
								//"devInfo": device.imei
						}, function(result) {
							var _result = new X2JS().xml2json(result);
							console.log(_result.string.__text);
							var _info = JSON.parse(_result.string.__text);

							if(_info.errorCode === 0 || _info.errorCode === "0") {
								this.User = _info.User;

								// 存储本地localStorage
								localStorage.username = username;
								localStorage.userpassword = password;
								localStorage.userfinger = $('.userfinger').prop('checked');

								loginPanel.state = "LOGINED";
								loginPanel.name = username;
								$.ajax({
									type: "GET",
									url: esri.config.defaults.io.proxyUrl + this.User.FileUrl,
									success: MAP.mapAppInit
								});
							} else {
								layer.open({
									content: _info.errorMessage,
									skin: 'msg',
									time: 3 //2秒后自动关闭
								});
							}
						})
					},
					// 关闭登录窗口
					close: function() {
						console.log("close")
						loginPanel.showLogin = false;
					},
					// 退出
					logout: function() {
						var PROXY_URI = "http://117.34.70.42:26060/proxy/proxy.jsp?";
						var MOBILE_SERVICE = PROXY_URI + "http://27.17.26.116:8019/MobileServer.asmx"; //WebService服务地址

						var M_LOGOUT_URI = MOBILE_SERVICE + "/Logout";
						
						// 反序列化json字符串为对象
						var _user = JSON.parse(window.localStorage.User);
						
						if(!_user) {
							// 用户登录信息不存在
							window.location.href = "loginReg.html";
							return;
						}
						
						$.ajax({
							type: 'POST',
							url: M_LOGOUT_URI,
							data: {
								strUNo: "", //用户唯一主键，对应登录返回内容的UNO
								strName: "" , //用户登录名，对应UName
							},
							success: function(response) {
								var result = JSON.parse(response.firstChild.innerHTML);
								console.log(result);

								// 用于测试工作流程
								 result.errorCode = 0;

								if(result.errorCode === 0) {
									// 成功退出
									window.location.href = "loginReg.html";
								} else if(result.errorCode === 2) {
									alert(result.errorMessage);
								}
							}
						});

					}
				},
				watch: {
					"showLogin": function(n, o) {
						if(loginPanel.state === "LOGINED") {
							// 如果已经登陆过则不向下执行登录判断的操作
							return;
						}
						if(n) {
							// 检查登录
							try {
								var _logined = checkFingerLogined();
								if(_logined) {
									this.showLogin = false;
								}
							} catch(err) {
								this.showLogin = true;
							}
						}
					}
				}
			})

			// 地图切换
			new Vue({
				el: '.mapSwitcher',
				data: {
					imageryLayer: null,

					baseLayer: null,

				},
				created: function() {
					this.imageryLayer = map.getLayer("影像地图");
					this.baseLayer = map.getLayer("电子政务地图");
				},
				methods: {
					showImageryLayer: function() {
						if(this.imageryLayer.visible) {
							this.imageryLayer.hide();
							console.log("imageryLayer hide");
						} else {
							this.imageryLayer.show();
							console.log("imageryLayer show");
						}
					},
					showBaseLayer: function() {
						if(this.baseLayer.visible) {
							this.baseLayer.hide();
							console.log("baseLayer hide");
						} else {
							this.baseLayer.show();
							console.log("baseLayer show");
						}
					}
				}
			});
		};

		//		$.ajax({
		//			type: "GET",
		//			url: MAP_INFO_CONFIG,
		//			success: _mapAppInit
		//		});

		$('#login_close').on('click', function() {
			loginPanel.close();
		});

		// 地图初始化
		init();

	}

	// 添加图层，（默认隐藏，树选中后回显）
	var titlelayers = [];
	var projectlayers = [];

	// 记录功能2图层管理中选中树的id
	var titletree = [];

	function _createTitleLayers() {
		var treedata = _treeDataConvertor();
		console.log(treedata);
		var _$basetree = $("#basetree");
		$.jstree.destroy()
		_$basetree.on("changed.jstree", function(e, data) {
			var i, j, r = [];
			for(i = 0, j = data.selected.length; i < j; i++) {
				r.push(data.instance.get_node(data.selected[i]).text);
			}
			titletree = r;
			console.log("Selected: " + r.join(", "));
			$(titlelayers).each(function(k, v) {
				v.hide();
			});
			$(r).each(function(_k, _v) {
				var _layerId = _v;
				var _layer = map.getLayer(_layerId);
				if(_layer)
					_layer.show();
			})
		});
		_$basetree.jstree({
			"core": {
				"data": treedata,
				"themes": {
					"icons": false
				}
			},
			"plugins": [
				"wholerow",
				"checkbox"
			]
		});
		_$basetree.on('ready.jstree', function() {
			//$("#basetree").jstree("open_all");
		});
	};

	/**
	 * 配置文件树结构转换为标准jsTree树结构
	 */
	function _treeDataConvertor() {
		var titlemap = dojoConfig.appdata.title_map.node;
		var _treedata = [];
		$(titlemap).each(function(k, v) {
			var layer = {
				"icon": "esri-icon-feature-layer",
				"text": v.name,
				"url": v.url,
				"type": v.LayerType,
				"nodeType": v.nodeType
			};
			if(v._nodeType == "Group") {
				layer.icon = "esri-icon-layers";
				var _child = layer.children = [];
				_appendChildren(v, _child, titlelayers);
			}
			_addLayer(layer, titlelayers);
			_treedata.push(layer)
		});
		return _treedata;
	}

	//	添加子图层
	function _appendChildren(v, _child, _list) {
		$(v.node).each(function(_k, _v) {
			var _layer = {
				"icon": "esri-icon-feature-layer",
				"text": _v.name,
				"url": _v.url,
				"type": _v.LayerType,
				"nodeType": _v._nodeType,
				"layerids": _v.layerids
			};
			if(_v._nodeType == "Group") {
				_layer.icon = "esri-icon-layers";
				var _layerchild = _layer.children = [];
				_appendChildren(_v, _layerchild, _list);
			}
			_addLayer(_layer, _list)
			_child.push(_layer)
		});
	}

	function _addLayer(config, list) {
		if(config.type == "TIL") {
			var _opacity = config.alpha || DEFAULT_OPACITY; // 获取图层透明度
			list.push(
				map.addLayer(new ArcGISTiledMapServiceLayer(config.url, {
					id: config.text,
					visible: false,
					opacity: _opacity
				})));
		} else if(config.type == "DYN") {
			var _opacity = config.alpha || DEFAULT_OPACITY; // 获取图层透明度
			var dyn = new ArcGISDynamicMapServiceLayer(config.url, {
				id: config.text,
				visible: false,
				opacity: _opacity
			});
			list.push(dyn);
			map.addLayer(dyn);
		}
	}

	var project_tree = [];
	// 初始化项目树
	function _createProjectTree() {
		var treedata = _projectTreeDataConvertor();
		console.log("dynamic-map", treedata);
		$("#projecttree")
			.on("changed.jstree", function(e, data) {
				var i, j, r = [];
				for(i = 0, j = data.selected.length; i < j; i++) {
					r.push(data.instance.get_node(data.selected[i]).text);
				}
				project_tree = r;
				map.infoWindow.hide();
				console.log("Selected: " + r.join(", "));
				$(projectlayers).each(function(k, v) {
					v.hide();
				});
				$(r).each(function(_k, _v) {
					var _layerId = _v;
					var _layer = map.getLayer(_layerId);
					if(_layer)
						_layer.show();
				})

			})
			.jstree({
				"core": {
					"data": treedata,
					"themes": {
						"icons": false
					}
				},
				"plugins": [
					"wholerow",
					"checkbox"

				]
			}).on('ready.jstree', function() {
				//$("#projecttree").jstree("open_all");
			});
	}

	function _projectTreeDataConvertor() {
		var dynamic_map = dojoConfig.appdata.dynamic_map.node;
		var _treedata = [];
		$(dynamic_map).each(function(k, v) {
			var _layerids = v.layerids;
			if(!_layerids) {
				_layerids = getIds(v.name)
			}
			var layer = {
				"icon": "esri-icon-feature-layer",
				"text": v.name,
				"url": v.url,
				"type": "PROJECT",
				"nodeType": v._nodeType,
				"outfileds": v.outfields,
				"layerids": _layerids
			};
			if(v._nodeType == "Group") {
				layer.icon = "esri-icon-layers";
				var _child = layer.children = [];
				_appendChildProject(v, _child, projectlayers, projectlayers);
			}
			_addProjectLayer(layer, projectlayers);
			_treedata.push(layer)
		});
		return _treedata;
	}

	//	添加子项目
	function _appendChildProject(v, _child, _list) {
		$(v.node).each(function(_k, _v) {
			var _layerids = _v.layerids;
			if(!_layerids) {
				_layerids = getIds(_v.name)
			}
			var _layer = {
				"icon": "esri-icon-feature-layer",
				"text": _v.name,
				"url": _v.url,
				"type": "PROJECT",
				"nodeType": _v._nodeType,
				"outfileds": v.outfields,
				"layerids": _layerids
			};
			if(_v._nodeType == "Group") {
				_layer.icon = "esri-icon-layers";
				var _layerchild = _layer.children = [];
				_appendChildProject(_v, _layerchild, _list);
			}
			_addProjectLayer(_layer, _list)
			_child.push(_layer)
		});
	}

	function _addProjectLayer(config, list) {
		if(config.type == "PROJECT" && config.nodeType !== "Group") {
			var _opacity = config.alpha || DEFAULT_OPACITY; // 获取图层透明度
			var _project = new ArcGISDynamicMapServiceLayer(config.url, {
				id: config.text,
				visible: false,
				opacity: _opacity,
			});
			list.push(_project);
			map.addLayer(_project);

			//			var layer = map.addLayer(new FeatureLayer(config.url + "/" + config.layerids, {
			//				id: config.text,
			//				infoTemplate: autotemplate(config.outfileds),
			//				outFields: ["*"],
			//				visible: false
			//			}));
			//			list.push(layer);
		}
	}

	function _createBaseMaps() {
		var basemap = dojoConfig.appdata.base_map.node;
		var fistLayer = true; //默认显示第一个图层
		var _layers = [];
		$.each(basemap, function(k, v) {
			var _basemap = v;
			_layers.push(_createBaseMap(map, {
				"name": _basemap.name,
				"url": _basemap.url,
				"datetime": _basemap.datetime
			}, fistLayer));
			if(fistLayer) {
				fistLayer = !fistLayer;
			}
		});
		map.addLayers(_layers);
	}

	function _createBaseMap(_map, config, show) {
		if(!_map || !config)
			return;
		return new ArcGISTiledMapServiceLayer(config.url, {
			id: config.name,
			visible: show //控制图层是否显示
		});
	}

	// 绘制要素
	function _drawGraphics(features, type) {
		if(!features) return;
		var _symbol;
		if(type === "dmlayer") {
			_symbol = DEFAULT_MARKER
			for(var i in features) {
				var feature = features[i];
				// 自动生成模板代码
				//				var attr = feature.attributes;
				//				var _fieldInfos = [];
				//				for(var a in attr) {
				//					_fieldInfos.push({
				//						fieldName: a,
				//						visible: true,
				//						label: getAliasFromKey(a)
				//					});
				//				}
				//				var _template = new PopupTemplate({
				//					fieldInfos: _fieldInfos
				//				});

				var _g = new Graphic(feature.geometry, _symbol, feature.attributes, template);
				dmlayer.add(_g);
			}
		} else if(type === "dllayer") {
			dllayer.hide();
			_symbol = LINE_SYMBOL;
			for(var i in features) {
				var feature = features[i];
				var _g = new Graphic(feature.geometry, _symbol, feature.attributes, template);
				dllayer.add(_g);
			}
		}
	}

	function drawingMeasure(geometry) {
		if(geometry.type == "point") {
			drawEnd({
				"geometry": geometry
			});
		}
		if(geometry.type == "polyline") {
			var _g = new Graphic(geometry, LINE_SYMBOL);
			var lengths = geometryEngine.planarLength(geometry, "meters").toFixed(3);
			console.log(lengths);

			map.graphics.clear(); // 清空现有绘制数据
			map.graphics.add(_g); // 添加新的要素

			if(!vm_measurelayer.target) {
				vm_measurelayer.target = {
					"type": "line",
					"graphic": _g,
					"lengths": lengths,
				}
				vm_measurelayer.measureGraphics.push(vm_measurelayer.target);
			} else {
				vm_measurelayer.target = {
					"type": "line",
					"graphic": _g,
					"lengths": lengths,
				}
				vm_measurelayer.measureGraphics.splice(vm_measurelayer.measureGraphics.length - 1, 1, vm_measurelayer.target);
			}
		} else if(geometry.type == "polygon") {
			var _g = new Graphic(geometry, POLYGON_SYMBOL);
			//var lengths = geometryEngine.planarLength(geometry, "meters").toFixed(3);
			var areas = geometryEngine.planarArea(geometry, "hectares").toFixed(3);

			map.graphics.clear(); // 清空现有绘制数据
			map.graphics.add(_g); // 添加新的要素

			if(!vm_measurelayer.target) {
				vm_measurelayer.target = {
					"type": "polygon",
					"graphic": _g,
					//"lengths": lengths,
					"areas": areas
				}
				vm_measurelayer.measureGraphics.push(vm_measurelayer.target);
			} else {
				vm_measurelayer.target = {
					"type": "polygon",
					"graphic": _g,
					//"lengths": lengths,
					"areas": areas
				}
				vm_measurelayer.measureGraphics.splice(vm_measurelayer.measureGraphics.length - 1, 1, vm_measurelayer.target);
			}
		}
	}

	// 绘制结束 返回对象
	function drawEnd(e) {
		//drawTool.deactivate(); //禁止绘制状态
		//vm_measurelayer.drawing = false;
		if(e.geometry.type == "point") {
			// 画点不需要提示
			getLocation(e);
			return;
		}
		if(e.geometry.type == "polyline") {
			getLength(e);
		} else if(e.geometry.type == "polygon") {
			getAreaAndLength(e);
		}
	}

	// 获取位置坐标
	function getLocation(e) {
		console.log("point", e);
		var _g = new Graphic(e.geometry, DEFAULT_MARKER);
		// 推送入测量队列
		vm_measurelayer.measureGraphics.push({
			"type": "point",
			"graphic": _g,
			"lon": e.geometry.x.toFixed(6),
			"lat": e.geometry.y.toFixed(6)
		});
		layer.closeAll();
	}

	// 进行面积和长度量算
	function getAreaAndLength(e) {
		var _g = new Graphic(e.geometry, POLYGON_SYMBOL);
		var areas = geometryEngine.planarArea(e.geometry, "hectares").toFixed(3);
		var lengths = geometryEngine.planarLength(e.geometry, "meters").toFixed(3);
		// 推送入测量队列
		vm_measurelayer.measureGraphics.push({
			"type": "polygon",
			"graphic": _g,
			"lengths": lengths,
			"areas": areas
		});
	};

	function getLength(e) {
		var _g = new Graphic(e.geometry, LINE_SYMBOL);
		var lengths = geometryEngine.planarLength(e.geometry, "meters").toFixed(3);
		console.log(lengths);
		// 推送入测量队列
		//		vm_measurelayer.measureGraphics.push({
		//			"type": "line",
		//			"graphic": _g,
		//			"lengths": lengths
		//		});
	}

	function autotemplate(fields) {
		if(!fields) {
			return;
		}
		var _fields = fields.split(",");
		if(!_fields) {
			return;
		}
		var _fieldInfos = [];
		for(var f in _fields) {
			if(!getKeyFromAlias(_fields[f]))
				continue;
			_fieldInfos.push({
				fieldName: getKeyFromAlias(_fields[f]),
				visible: true,
				label: _fields[f]
			});
		}
		return new PopupTemplate({
			fieldInfos: _fieldInfos
		});
	}

	function autoFields(feature) {
		var attr = feature.attributes;
		var _fieldInfos = [];
		for(var a in attr) {
			if(a === "OBJECTID" || a === "Shape" || a === "Shape_Length" || a === "Shape_Area" ||
				a === "SHAPE_Length" || a === "SHAPE_Area") {
				continue;
			}
			if(!attr[a] || attr[a] === "Null") {
				continue;
			}
			_fieldInfos.push({
				fieldName: a,
				visible: true,
				label: getAliasFromKey(a)
			});
		}
		return new PopupTemplate({
			fieldInfos: _fieldInfos
		});
	}

	// WGS2BJ54
	function WGS2BJ54(coords, callback) {

		$.get(esri.config.defaults.io.proxyUrl + "http://27.17.26.115:3310/GPSService.asmx/WGS2BJ54" + "?BL=" + coords.longitude + ";" + coords.latitude, {}, function(result) {
			var _coordsJSON = new X2JS().xml2json(result);
			console.log(_coordsJSON);
			callback(_coordsJSON.ArrayOfDouble.double[0], _coordsJSON.ArrayOfDouble.double[1] - 3000009.0);
		});
	}

});
